package cn.iocoder.yudao.module.erp.controller.admin.contacts.supplier;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.erp.controller.admin.contacts.supplier.vo.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.contacts.supplier.SupplierDO;
import cn.iocoder.yudao.module.erp.service.contacts.supplier.SupplierService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "管理后台 - ERP供应商")
@RestController
@RequestMapping("/erp/supplier")
@Validated
public class SupplierController {

    @Resource
    private SupplierService supplierService;

    @PostMapping("/create")
    @Operation(summary = "创建供应商")
    @PreAuthorize("@ss.hasPermission('erp:supplier:create')")
    public CommonResult<Long> createSupplier(@Valid @RequestBody SupplierSaveReqVO createReqVO) {
        return success(supplierService.createSupplier(createReqVO)).setMsg("创建成功");
    }

    @PutMapping("/update")
    @Operation(summary = "更新供应商")
    @PreAuthorize("@ss.hasPermission('erp:supplier:update')")
    public CommonResult<Boolean> updateSupplier(@Valid @RequestBody SupplierSaveReqVO updateReqVO) {
        supplierService.updateSupplier(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除供应商")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('erp:supplier:delete')")
    public CommonResult<Boolean> deleteSupplier(@RequestParam("id") Long id) {
        supplierService.deleteSupplier(id);
        return success(true);
    }

    @DeleteMapping("/delete-any")
    @Operation(summary = "批量删除供应商")
    @Parameter(name= "ids", description = "编号列表", required = true)
    @PreAuthorize("@ss.hasPermission('erp:supplier:delete')")
    public CommonResult<Boolean> deleteSuppliers(@RequestParam("ids") Collection<Long> idList) {
        supplierService.deleteSuppliers(idList);
        return success(true).setMsg("批量删除供应商成功");
    }

    @PostMapping("/import")
    @Operation(summary = "导入供应商")
    @PreAuthorize("@ss.hasPermission('erp:supplier:import')")
    @Parameters({
            @Parameter(name="file",description = "Excel文件", required = true),
            @Parameter(name="updateSupport", description = "是否支持更新已存在的数据，默认为false", example = "true")
    })
    public CommonResult<SupplierImportRespVO> importExcel(@RequestParam(value = "file") MultipartFile file,
                                                          @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
        List<SupplierImportExcelVO> list = ExcelUtils.read(file, SupplierImportExcelVO.class);
        return success(supplierService.importSupplierList(list, updateSupport,getLoginUserId()));
    }
    @GetMapping("/get-import-template")
    @Operation(summary = "获得导入供应商模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 手动创建导出 demo
        List<SupplierImportExcelVO> list = Arrays.asList(
                SupplierImportExcelVO.builder().name("江易行科技").code("GYS001").contacterName("mxx").mobile("17751591234")
                        .email("1608881588@qq.com").description("开发软件的").groupName("制造业").build()
        );
        // 输出
        ExcelUtils.write(response, "客户导入模板.xls", "客户列表", SupplierImportExcelVO.class, list);
    }
    @GetMapping("/get")
    @Operation(summary = "获得供应商")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:supplier:query')")
    public CommonResult<SupplierRespVO> getSupplier(@RequestParam("id") Long id) {
        SupplierDO supplier = supplierService.getSupplier(id);
        return success(BeanUtils.toBean(supplier, SupplierRespVO.class));
    }

    @GetMapping("/simple-list")
    @Operation(summary = "获取供应商精简列表")
    @PreAuthorize("@ss.hasPermission('erp:supplier:query')")
    public CommonResult<List<SupplierRespVO>> getSimpleSupplier() {
        SupplierPageReqVO supplierPageReqVO = new SupplierPageReqVO();
        supplierPageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        PageResult<SupplierDO> supplierPage = supplierService.getSupplierPage(supplierPageReqVO);
        return success(convertList(supplierPage.getList(), item -> new SupplierRespVO().setId(item.getId())
                .setName(item.getName()).setContacterName(item.getContacterName()).setMobile(item.getMobile())));
    }

    @GetMapping("/page")
    @Operation(summary = "获得供应商分页")
    @PreAuthorize("@ss.hasPermission('erp:supplier:query')")
    public CommonResult<PageResult<SupplierRespVO>> getSupplierPage(@Valid SupplierPageReqVO pageReqVO) {
        PageResult<SupplierDO> pageResult = supplierService.getSupplierPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, SupplierRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出供应商 Excel")
    @PreAuthorize("@ss.hasPermission('erp:supplier:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportSupplierExcel(@Valid SupplierPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<SupplierDO> list = supplierService.getSupplierPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "供应商.xls", "数据", SupplierRespVO.class,
                        BeanUtils.toBean(list, SupplierRespVO.class));
    }

}